<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class VipAddressController extends Controller
{	

    //前台购物车页
    public function getAdd()
    {
    	return view('user.address.add');
    }

    //地址添加

    public function postInsert(Request $request)
    {

    	//自动数据验证
    	$this->validate($request, [
        	'getman' => 'required',
        	'phonenum' => 'required|regex:[^\d{11}$]',       	
        	'address'=>'required'
    	],[
    		'getman.required'=>'收件人不能为空',
    		'phonenum.required'=>'电话不能为空',
    		'phonenum.regex'=>'请输入11位手机号码',
    		'address.required'=>'地址不能为空'
    	]);
    	session(['id'=>2]);
    	$id = $request->session()->all();

    	$data=$request->except('_token');

    	$data['uid']=$id['id'];
    	$data['addtime']=time();
    	
    	$res=DB::table('ym_address')->insert($data);
    	// dd($res);

    	if($res){
    		return redirect('/home/user/address/index')->with('success','添加地址成功');
    	}else{
    		return back()->with('error','添加地址失败');
    	}


    }

    //地址列表

    public function getIndex(Request $request)

    {
    	if(empty($request->input('keywords'))){
			$info=DB::table('ym_address')->orderBy('addtime','desc')->paginate($request->input('num',5));
		} else{

			$info=DB::table('ym_address')->orderBy('addtime','desc')->where('getman','like','%'.$request->input('keywords').'%')->paginate($request->input('num',5));
		}   	
    	// dd($data);


    	//解析模板
    	return view('user.address.index',['info'=>$info]);

    }

    //地址修改
    public function getEdit($id)
    {
    	$res=DB::table('ym_address')->where('id',$id)->first();
    	//解析模板
    	return view('user.address.edit',['info'=>$res]);
    }

    //地址更新数据
    public function postUpdate(Request $request)
    {
    	
    	$data=$request->except('_token');
    	$data['addtime']=time();
    	$id=$request->input('id');
    	$res=DB::table('ym_address')->where('id',$id)->update($data);

    	if($res){
            return redirect('/home/user/address/index')->with('success','修改地址成功');
        }else{
            return back()->with('error','修改地址失败');
        }
    }

    //地址删除

    public function getDelete($id)
    {
    	
    	$res=DB::table('ym_address')->where('id',$id)->delete();

    	if($res){
            return redirect('/home/user/address/index')->with('success','修改删除成功');
        }else{
            return back()->with('error','修改删除失败');
        }
    }
    
}
